<template>
  <div class="_replayVideo">
    <div class="card_left">
      <Card :bordered="true" dis-hover>
        <p slot="title">搜索</p>
        <Form ref="formSearch" :model="fromData" label-position="right" :label-width="80" :rules="ruleValidate">
          <FormItem label="车牌号" prop="carPlateNo">
            <Input v-model="fromData.carPlateNo" clearable placeholder="请输入车牌号" prefix="md-car" suffix="ios-search" />
          </FormItem>
          <FormItem label="选择日期" prop="timeData">
            <DatePicker v-model="fromData.timeData" placeholder="请选择日期" type="date"></DatePicker>
          </FormItem>
          <FormItem label="开始时间" prop="begs">
            <TimePicker v-model="fromData.begs" format="HH:mm:ss" placeholder="请选择开始时间"></TimePicker>
          </FormItem>
          <FormItem label="结束时间" prop="ends">
            <TimePicker v-model="fromData.ends" format="HH:mm:ss" placeholder="请选择结束时间"></TimePicker>
          </FormItem>
          <FormItem label="">
            <Button type="primary" @click="trackFun('formSearch')">搜索</Button>
            <Button type="dashed" @click="reset()">重置</Button>
          </FormItem>
        </Form>
      </Card>
      <Card :bordered="true" dis-hover style="margin: 10px 0 0 0;height: 100%;">
        <p slot="title">视频列表</p>
        <div style="height: 100%;" ref="tableH">
          <Table ref="selection" :height="tableHeight" :loading="loading" :columns="columns4" :data="listData" border></Table>
        </div>
      </Card>
    </div>
    <div style="width: calc(100% - 410px);height: 100%;background: #fff;float: right">
      <cptVideo ref="videoOn"></cptVideo>
    </div>


    <Modal title="选择通道播放" v-model="channelType" :mask-closable="false" :footer-hide="true">
      <template>
        <div style="padding: 0 0 53px 0;">
          <wzTbale ref="wzTbale" :tableData="tableData" ></wzTbale>
          <div class="demo-drawer-footer"  style="z-index: 3;">
            <Button style="margin-right: 8px" @click="channelType = false">取消</Button>
            <Button type="primary" @click="selectTable">确定</Button>
          </div>
        </div>
      </template>
    </Modal>
  </div>
</template>
<script>
import cptVideo from './CptVideo'
import videoOne from '../../../assets/icon_s_fors.png'
import videoPair from '../../../assets/icon_s_forB.png'
import wzTbale from "../../../components/table/table";

export default {
  components: {
    cptVideo,
    videoOne,
    videoPair,
    wzTbale
  },
  data() {
    return {
      loading:false,
      tableData: {
        page: false,//分页是否使用
        where: {},//搜索条件
        height: 'auto',//表格高度 auto
        columns: [//表头数据
          { type: 'selection', width: 60, align: 'center',},
          {  title: '通道', width: 80, key: 'chnIndex',render:(h,params) => {
              return h('span','CH'+(params.row.chnIndex + 1))
            }  },
          {  title: '时间', key: 'timeTitle' },
        ],
        dataList:[]
      },
      channelType:false,//通道选择
      ruleValidate: {
        carPlateNo: [
          {required: true, message: '请输入车牌号', trigger: 'blur'}
        ],
        timeData: [
          {type:'date',required: true, message: '请选择日期', trigger: 'blur'}
        ],
        begs: [
          {required: true, message: '请选择开始时间', trigger: 'blur'}
        ],
        ends: [
          {required: true, message: '请选择结束时间', trigger: 'blur'}
        ],
      },
      fromData: {
        timeData: new Date(),
        BEG: 0,
        END: 86399,
        begs: '00:00:00',
        ends: '23:59:59',
      },

      listData: [],
      tableHeight: 0,
      columns4: [
        {
          title: '通道', width: 61, key: 'chn', render: (h, params) => {
            return h('span', 'CH' + (params.row.chn + 1))
          }
        },
        {
          title: '时间', key: 'beg', width: 204, render: (h, params) => {
            var data = params.row
            return h('span', '20' + data.year + '/' + data.mon + '/' + data.day + ' ' + this.timeConversion(data.beg) + ' - ' + this.timeConversion(data.end))
          }
        },
        {
          title: '操作', key: 'action', render: (h, params) => {
            return h('div', {style: {display: 'flex'}},
              [h('img', {
                attrs: {src: videoOne}, style: {width: '18px', height: '18px', margin: '0 7px 0 0', cursor: 'pointer'},
                on: {
                  click: () => {
                    //单视频播放
                    this.$refs.videoOn.playVideo(params.row.PlaybackUrlWs)
                  }
                }
              }),
                h('i', {style: {height: '15px', width: '1px', border: '1px solid #efefef',}}),
                h('img', {attrs: {src: videoPair}, style: {width: '18px', height: '18px', margin: '0 0 0 7px',cursor: 'pointer'},
                  on:{
                    click: () => {
                      //多通道视频播放
                      this.upShow(params.row)
                      // this.channelType = true;
                    }
                  }})
              ])

          }
        }
      ],
    }
  },
  computed: {//计算属性

  },
  beforeCreate() {//beforeCreate创建前状态

  },
  created() {//created创建完毕状态

  },
  beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

  },
  mounted() {//mounted 挂载结束状态
    let that = this
    that.getJsession()//视频 登录
    that.$nextTick(function () {
      that.tableHeight = this.$refs.tableH.offsetHeight;
    })

  },
  methods: {//执行的方法
    reset(){
      this.listData= []
      this.fromData = {
        timeData: new Date(),
        carPlateNo:'',
        BEG: 0,
        END: 86399,
        begs: '00:00:00',
        ends: '23:59:59',
      }
    },
    upShow(data){
      const videoFileList = this.listData
      let chnPlayUrl = []
      for (var j = 0; j < videoFileList.length; j++) {
        var videoFile = videoFileList[j]
        let playUrl = videoFile.PlaybackUrlWs
        let chn = videoFile.chn
        //时间是否符合
        if (!this.videoFileTimeTally(videoFile, data)) {
          continue
        }
        // 单个通道
        if (!chnPlayUrl[chn]) {
          chnPlayUrl[chn] = []
        }
        chnPlayUrl[chn].push({
          timeTitle: videoFile.beginDate+"-"+ this.timeConversion(videoFile.end),
          url: playUrl,
          // chn: chnNames[chn],
          chnIndex: chn,
          'LAY_CHECKED': true
        })
      }
      let tableData = []
      let Selected = []
      for (var index in chnPlayUrl) {
        if (chnPlayUrl[index].length > 0) {
          tableData.push(chnPlayUrl[index][0])
          Selected.push(JSON.parse(index))
        }
      }
      for (let i = 0;i <tableData.length;i++){
        tableData[i]._checked = true
      }
      this.tableData.dataList = tableData
      this.selectedRowKeys = Selected
      console.log(this.tableData)
      this.channelType = true;
    },

    videoFileTimeTally(videoFile, mulFileInfo) {
      var beginDateTime = this.dateTimeStrToMillisecond(mulFileInfo.beginDate)
      var endDateTime = this.dateTimeStrToMillisecond(mulFileInfo.endDate)
      var range1 = [beginDateTime, endDateTime]
      var videoFileBeginDateTime = this.dateTimeStrToMillisecond(videoFile.beginDate)
      var videoFileEndDateTime = this.dateTimeStrToMillisecond(videoFile.endDate)
      var range2 = [videoFileBeginDateTime, videoFileEndDateTime]
      if (this.numberIsBetweenRange(videoFileBeginDateTime, range1) ||
        this.numberIsBetweenRange(videoFileEndDateTime, range1) ||
        this.numberIsBetweenRange(beginDateTime, range2) ||
        this.numberIsBetweenRange(endDateTime, range2)
      ) {
        return true
      }
      return false
    },
    numberIsBetweenRange(a, range) {
      return a >= range[0] && a <= range[1]
    },
    dateTimeStrToMillisecond(str) {
      if (!str) {
        return 0
      }
      var arr = str.split(/[- : \/]/)
      return Date.parse(new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]))
    },

    selectTable(){
      this.$refs.wzTbale.tableDataSelected() //获取表格点击的数据
      this.$refs.videoOn.multiChannelVideo(this.$refs.wzTbale.tableDataSelected()) // 给子组件传视频数据
      this.channelType = false //关闭窗口

    },
    // 获取 会话号  与储存本地会话号
    getJsession() {
      let that = this
      var jsession = localStorage.getItem('ConversationUuid')
      if (!jsession) {
        that.axios.post("zdaqweb/StandardApiAction_login.action?account=admin&password=shipinyou666", {}).then(res => {
          localStorage.setItem('ConversationUuid', res.data.jsession)
        }).catch(err => {
          console.log('失败', err);
        })
      }
    },
    //搜索
    trackFun(name) {
      var that = this
      this.loading = true
      that.$refs[name].validate((valid) => {
        if (valid) {//正则判断使用
          that.$refs.videoOn.stopVideo()
          if (localStorage.getItem('ConversationUuid') && that.fromData.carPlateNo) {// 视频 token 是否存在
            var parameter = {
              'jsession': localStorage.getItem('ConversationUuid'),
              'vehiIdno': that.fromData.carPlateNo
            }
            let data = that.qs.stringify(parameter);
            that.axios.post('zdaqweb/StandardApiAction_getDeviceByVehicle.action', data, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {

              if (res.data.result != 0 || res.data.result == 5) {// 失败 登录
                localStorage.removeItem('ConversationUuid');
                that.getJsession()
              } else {

                // 数据处理
                that.fromData.BEG = that.handleChange(that.fromData.begs);//开始时间转 秒
                that.fromData.END = that.handleChange(that.fromData.ends);//结束时间转 秒


                that.fromData.YEAR = that.public.timeFormatting(that.fromData.timeData, "yyyy")
                that.fromData.MON = that.public.timeFormatting(that.fromData.timeData, "MM")
                that.fromData.DAY = that.public.timeFormatting(that.fromData.timeData, "dd")


                var itemData = {
                  'DevIDNO': res.data.devices[0].did,
                  'jsession': localStorage.getItem('ConversationUuid'),
                  'ARM1': 0,
                  'ARM2': 0,
                  'CHN': -1,
                  'FILEATTR': 2,
                  'LOC': 1,
                  'RECTYPE': -1,
                  'RES': 0,
                  'STORE': 0,
                  'STREAM': -1
                }
                const requestParameters = Object.assign({}, itemData, that.fromData)
                let dataTransform = that.qs.stringify(requestParameters);
                that.axios.get('zdaqweb/StandardApiAction_getVideoFileInfo.action?' + dataTransform).then(res => {
                  if(res.data.result == 46){
                    that.$Message.error('设备回应失败');
                    that.loading = false
                    return
                  }
                  that.listData = [];
                  if (res.data.result == 0) {
                    if (res.data.files) {
                      var data = res.data.files
                      data.sort(function (a, b) {
                        return a.beg - b.beg
                      })
                      for (let i = 0; i < data.length; i++) {
                        data[i].beginDate = '20' + data[i].year + '-' + data[i].mon + '-' + data[i].day + ' ' + that.timeConversion(data[i].beg)
                        data[i].endDate = '20' + data[i].year + '-' + data[i].mon + '-' + data[i].day + ' ' + that.timeConversion(data[i].end)
                      }
                      that.listData = data
                      this.loading = false
                    } else {
                      that.$Message.error('无文件信息');
                      that.loading = false

                    }
                  }
                })
              }
            }).catch(err => {
              console.log('失败', err);
            })
          }else{
            that.getJsession()
          }
        } else {
          this.$Message.error('请正确填写表单')
        }
      })
    },
    // 时间转换秒
    handleChange(value,name) {
      var hour = value.split(':')[0];
      var min = value.split(':')[1];
      var sec = value.split(':')[2];
      return Number(hour * 3600) + Number(min * 60) + Number(sec)
    },
    //时间转换
    timeConversion(value) {
      var theTime = parseInt(value)// 需要转换的时间秒
      var theTime1 = 0// 分
      var theTime2 = 0// 小时
      var theTime3 = 0// 天
      if (theTime > 60) {
        theTime1 = parseInt(theTime / 60)
        theTime = parseInt(theTime % 60)
        if (theTime1 > 60) {
          theTime2 = parseInt(theTime1 / 60)
          theTime1 = parseInt(theTime1 % 60)
          if (theTime2 > 24) {
            //大于24小时
            theTime3 = parseInt(theTime2 / 24)
            theTime2 = parseInt(theTime2 % 24)
          }
        }
      }
      var result = ''
      if (theTime > 0) {//秒
        if (parseInt(theTime) < 10) {
          result = '0' + parseInt(theTime) + ''
        } else {
          result = '' + parseInt(theTime) + ''
        }
      } else {
        result = '00' + ''
      }


      if (theTime1 > 0) {//分
        if (parseInt(theTime1) < 10) {
          result = '0' + parseInt(theTime1) + ':' + result
        } else {
          result = '' + parseInt(theTime1) + ':' + result
        }
      } else {
        result = '00' + ':' + result
      }


      if (theTime2 > 0) {//小时
        if (parseInt(theTime2) < 10) {
          result = '0' + parseInt(theTime2) + ':' + result
        } else {
          result = '' + parseInt(theTime2) + ':' + result
        }
      } else {
        result = '00' + ':' + result
      }
      // if(theTime3 > 0) {
      //   result = ""+parseInt(theTime3)+"天"+result;
      // }
      return result
    },
  },
  watch: {//监听

  },
  props: {//接收来自父组件的数据

  },
  beforeUpdate() {//beforeUpdate 更新前状态

  },
  updated() {//updated 更新完成状态

  },
  beforeDestroy() {//beforeDestroy 销毁前状态

  },
  destroyed() {//destroyed 销毁完成状态

  }
}
</script>
<style lang="less">

._replayVideo {
  padding: 10px;
  height: 100%;

  .ivu-card-body {
    height: calc(100% - 51px);
  }
  .card_left {
    display: flex;
    flex-direction: column;
    width: 400px;
    height: 100%;
    float: left;
    background: #fff;
  }
}
</style>
